/*
 * @Author: ChaiHongJun
 * @Date: 2021-08-10 14:04:19
 * @LastEditors: ChaiHongJun
 * @LastEditTime: 2021-08-11 08:25:22
 * @version:
 * @Description: 区分开发和生产环境的打包模式
 * 命令行：
 * webpack  开发打包
 * webpack env production 生产打包
 */
const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const StylelintPlugin = require('stylelint-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
module.exports = (env, argv) => {
  const config = {
    mode: 'development',
    entry: './src/index.js',
    output: {
      filename: 'bundle.js',
      path: resolve(__dirname, 'dist')
    },
    //   optimization: {   ////开发环境优化CSS
    //   // minimize: false,
    //   // minimizer: [
    //   //   new CssMinimizerPlugin({
    //   //     parallel: true,  //使用多进程并发执行，提升构建速度
    //   //   }),
    //   // ]
    // },
    module: {
      rules: [
        // 使用资源模块处理字体
        {
          test: /\.(eot|svg|ttf|woff|woff2)$/i,
          type: 'asset/resource',
          generator: {
            filename: 'fonts/[name].[hash:5][ext]'
          }
        },
        //处理CSS
        {
          test: /\.css$/,
          use: [
            // 'style-loader',
            MiniCssExtractPlugin.loader,
            'css-loader',
            'postcss-loader',],
        },
        // 处理Less
        {
          test: /\.less$/,
          use: [
            // 'style-loader',
            MiniCssExtractPlugin.loader,
            'css-loader',
            'postcss-loader',
            'less-loader'
          ]
        },
        // 资源模块处理图片
        {
          test: /\.(png|jpe?g|gif)$/i,
          type: "asset",
          parser: {
            dataUrlCondition: {
              maxSize: 8 * 1024 // 8kb
            }
          },
          generator: {
            filename: 'images/[name].[hash:5][ext]'
          }
        },
        // 打包html中的图片
        {
          test: /\.html$/,
          loader: "html-loader",
          options: {
            minimize: false,
            esModule: false,
          }
        },
        // 编译JS
        {
          test: /\.m?js$/,
          exclude: /(node_modules|bower_components)/, //排除本地需要编译的目录
          use: {
            loader: 'babel-loader',
            options: {
              presets: [
                [
                  "@babel/preset-env",
                  {
                    //按需转换JS
                    useBuiltIns: "usage",
                    // corejs 版本
                    corejs: 3,
                    targets: "defaults",
                  }
                ]
              ]
            }
          }
        }
      ]
    },
    plugins: [
      // 打包前 清理输出目录
      new CleanWebpackPlugin(),
      //打包HTML页面
      new HtmlWebpackPlugin({
        title: 'webpack5',
        template: './src/template/index.ejs',
        filename: 'index.html',
        meta: {
          keywords: '关键词'
        },
        // 压缩html页面 开发环境不需要
        // minify: {
        //   collapseWhitespace: true,
        //   keepClosingSlash: true,
        //   removeComments: true,
        //   removeRedundantAttributes: true,
        //   removeScriptTypeAttributes: true,
        //   removeStyleLinkTypeAttributes: true,
        //   useShortDoctype: true
        // }
      }),
      //提取CSS到单独的CSS文件
      new MiniCssExtractPlugin({
        filename: "style/[name].[hash:5].css",
      }),
      new StylelintPlugin({
        //指定检查源文件所在目录
        files: ["./src/style/*.(css|less)"]
      }),

    ],
    devServer: {
      contentBase: resolve(__dirname, 'dist'),
      host: 'localhost',  // 配置启动ip地址
      port: 9090,  // 配置端口
      open: true, // 配置是否自动打开浏览器
      compress: true,
      liveReload: true, //热更新
      //配置代理 解决跨域
      proxy: {
        // http://localhost:8080/api
        "/api": {    // 这里的`/api`是自定义的
          // http://localhost:8080/api/users = >  https://api.github.com/api/users
          target: "https://api.github.com/", //这里是真实的接口baseURL
          //http://localhost:8080 => https://api.github.com
          changeOrigin: true,
          ws: true,
          secure: false,
          pathRewrite: {
            //去掉 '/api/'
            // http://localhost:8080/api/users = >  https://api.github.com/users
            "^/api": "", // 这里的`^/api`也是是自定义的
          },
        },
      }
    },
    target: 'web', //热更新
  }
  //生产环境的配置，需要额外的压缩功能
  if (env.production) {
    config.mode = "production",
      config.optimization = {
        minimize: true,   //优化CSS
        minimizer: [
          new CssMinimizerPlugin({
            parallel: true,  //使用多进程并发执行，提升构建速度
          }),
        ]
      },
      config.plugins = [
        // 打包前 清理输出目录
        new CleanWebpackPlugin(),
        //打包HTML页面
        new HtmlWebpackPlugin({
          title: 'webpack5',
          template: './src/template/index.ejs',
          filename: 'index.html',
          meta: {
            keywords: '关键词'
          },
          // 压缩html页面
          minify: {
            collapseWhitespace: true,
            keepClosingSlash: true,
            removeComments: true,
            removeRedundantAttributes: true,
            removeScriptTypeAttributes: true,
            removeStyleLinkTypeAttributes: true,
            useShortDoctype: true
          }
        }),
        //提取CSS到单独的CSS文件
        new MiniCssExtractPlugin({
          filename: "style/[name].[hash:5].css",
        }),
        new StylelintPlugin({
          //指定检查源文件所在目录
          files: ["./src/style/*.(css|less)"]
        }),
        // 图片压缩
        new ImageMinimizerPlugin({
          minimizerOptions: {
            // Lossless optimization with custom option
            // Feel free to experiment with options for better result for you
            plugins: [
              ["gifsicle", { interlaced: true }],
              ["jpegtran", { progressive: true }],
              ["optipng", { optimizationLevel: 5 }],
            ],
          },
          filter: (source, sourcePath) => {
            if (source.byteLength < 8 * 1024) { //小于8Kb不优化
              return false;
            }
            return true;
          },
          loader: false,
        }),
      ]
  }
  return config;
}